package com.sysu.simulation.helper;


import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.content.SharedPreferencesCompat;

import com.google.gson.Gson;

import java.lang.reflect.Type;

public class CacheHelper {
    private static final String PREF_NAME = "USER_PREF";

    // parse to json and save
    public static boolean save(Context context, Object o, String key_name) {
        remove(context, key_name);
        Gson gson = new Gson();
        String value = gson.toJson(o);
        SharedPreferences sp = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key_name, value);
        return editor.commit();
    }

    public static <T> T load(Context context, Type t, String key_name) {
        SharedPreferences sp = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        String value = sp.getString(key_name, null);
        Gson gson = new Gson();
        return gson.fromJson(value, t);
    }

    public static void remove(Context context, String key_name) {
        SharedPreferences sp = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key_name);
        // use apply method instead of commit
        SharedPreferencesCompat.EditorCompat.getInstance().apply(editor);
    }

    public static void clearAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        // use apply method instead of commit
        SharedPreferencesCompat.EditorCompat.getInstance().apply(editor);
    }


}
